﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System.Windows.Controls;
using System.Windows.Navigation;
using AdminApp.Web.Services;
using AdminApp.Controls;
using AdminApp.Resources;
using System.Linq;

namespace AdminApp.Views
{
    public partial class Session : Page
    {
        public Session()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void sessionDomainDataSource_LoadedData(object sender, LoadedDataEventArgs e)
        {

            if (e.HasError)
            {
                System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
                e.MarkErrorAsHandled();
            }
        }

        private void _addNew_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Web.Session session = new Web.Session();
            session.Title = ApplicationStrings.NewSessionTitle;
            session.Abstract = ApplicationStrings.NewSessionAbstract;

            DigitalSignageDomainContext context =
                sessionDomainDataSource.DomainContext as DigitalSignageDomainContext;
            context.Sessions.Add(session);
        }

        private void _delete_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (sessionDataGrid.SelectedItem != null)
            {
                QuestionWindow qw = new QuestionWindow(ApplicationStrings.DeleteSessionQuestion, DeleteSession);
                qw.Show();
            }
        }

        private void DeleteSession()
        {
            Web.Session session = sessionDataGrid.SelectedItem as Web.Session;
            DigitalSignageDomainContext context =
                    sessionDomainDataSource.DomainContext as DigitalSignageDomainContext;
            context.Sessions.Remove(session);
        }

        private void SearchControl_SearchTextChanged(object sender, AdminApp.Controls.SearchEventArgs args)
        {
            DigitalSignageDomainContext ctx = sessionDomainDataSource.DomainContext as DigitalSignageDomainContext;
            if (args.SearchText.Length > 0)
            {
                var result = from s in ctx.Sessions
                             where s.Title.ToLower().Contains(args.SearchText.ToLower()) ||
                                s.ShortTitle.ToLower().Contains(args.SearchText.ToLower())
                             select s;
                sessionDataGrid.ItemsSource = result;
            }
            else
            {
                sessionDataGrid.ItemsSource = ctx.Sessions;
            }
        }
    }
}
